<?php

/**
 * 
 * @author yuxun
 *
 */
class MatchCrossServerVController extends AdminBaseController {
	
	/**
	 * 手动添加页面
	 */
	public function handIndex(){
		$this->setTitle('匹配跨服列表(临时配置)');
	
		$filter = new PubFilter();
		$grid   = new PubGrid();
	
		$filter->addFilter('cross_server_name', 'input', '跨服名称');
	
		$params = $filter->get();
		$page = $this->R('page', '1');
		$m = $this->R('m');
		$params['m'] = $m;
		$header = MatchCrossServerVService::indexHeader('handIndex');
		if(PubFunc::isAjax()){
			$result = MatchCrossServerVService::indexData($params,'handIndex');
			$this->out = array(
					'count'     => $result['count'],
					'data'      => $result['data'],
					'result'    => true
			);
			$this->outType = 'json';
		}else{
			$order  = 'create_time';
			$url = PubFunc::ajaxUrl("?r=matchCrossServerV/handIndex", $params);
			$grid->addGrid($header, $url, array(
					'name'=>'数据',
					'order'=>array($order, 'desc'),
					'type'=>'matchCrossServerV/handIndex',
					'page'=>$page
			));
	
			$this->out['filter'] = $filter->show();
			$this->out['grid'] = $grid->show();
				
			$is_add = 1; //能添加
			$crossList = SystemService::searchInfo('cross');
			$reset_time = $crossList['reset_time'];
			$reset_time_2 = strtotime($reset_time);
			$reset_time_1 = strtotime ("-3 day", strtotime($reset_time));
			$nowTime = strtotime(date('Y-m-d H:i:00',time()));
			if($reset_time_1 <= $nowTime && $nowTime <= $reset_time_2){  //重置时间的前3天内
				$is_add = 2; //不可以添加
			}
			$this->out['is_add'] = $is_add;
		}
	}
	

	public function index(){
		$this->setTitle('匹配跨服列表(预备)');
	
		$filter = new PubFilter();
		$grid   = new PubGrid();
	
		$filter->addFilter('cross_server_name', 'input', '跨服名称');
	
		$params = $filter->get();
		$page = $this->R('page', '1');
		$m = $this->R('m');
		$params['m'] = $m;
		$header = MatchCrossServerVService::indexHeader('index');
		if(PubFunc::isAjax()){
			$result = MatchCrossServerVService::indexData($params,'index');
			$this->out = array(
					'count'     => $result['count'],
					'data'      => $result['data'],
					'result'    => true
			);
			$this->outType = 'json';
		}else{
			$order  = 'create_time';
			$url = PubFunc::ajaxUrl("?r=matchCrossServerV/index", $params);
			$grid->addGrid($header, $url, array(
					'name'=>'数据',
					'order'=>array($order, 'desc'),
					'type'=>'matchCrossServerV/index',
					'page'=>$page
			));
	
			$this->out['filter'] = $filter->show();
			$this->out['grid'] = $grid->show();
			
			$is_add = 1; //不能添加
			$crossList = SystemService::searchInfo('cross');
			$reset_time = $crossList['reset_time'];
			$reset_time_2 = strtotime($reset_time);
			$reset_time_1 = strtotime ("-3 day", strtotime($reset_time));
			$nowTime = strtotime(date('Y-m-d H:i:00',time()));
// 			echo date('Y-m-d H:i',$reset_time_2);echo '<br/>';
// 			echo date('Y-m-d H:i',$reset_time_1);echo '<br/>';
			if($reset_time_1 <= $nowTime && $nowTime <= $reset_time_2){  //重置时间的前3天内
				$is_add = 2; //可以添加			
			}
			$this->out['is_add'] = $is_add;
		}
	}
	
	
	public function add(){
		//查询跨服配置
		$crossList = SystemService::searchInfo('cross');
		$this->out['crossList'] = $crossList;
		
		//当前跨服关联的服务器
		$infoServer = MatchCrossServerVService::getMatchServer(0);
		$this->out['infoServer'] = $infoServer;
		
		//查询能够让匹配跨服选择的服（去除$id本身的关系的服务器）
		$otherInfoServer = MatchCrossServerVService::fitServer(0);
		
		
		$reset_time = $crossList['reset_time'];
		$reset_time_2 = strtotime($reset_time);
		$reset_time_1 = strtotime ("-3 day", strtotime($reset_time));
		$nowTime = strtotime(date('Y-m-d H:i:00',time()));
		if($reset_time_1 < $nowTime && $nowTime < $reset_time_2){  //重置时间的前3天内
			$this->setTitle('新建匹配跨服');
		}else{
			$this->setTitle('新建匹配跨服(临时配置)');
			//这里要剔除正式匹配跨服存在的数据
			$modMatchCrossSer = new ModMatchCrossSer();
			$game = PubBase::getCurrentGame();
			$useServer = $modMatchCrossSer->getAllServer($game);
			$useServerList = array();
			foreach ($useServer as $key=>$val){
				$useServerList[] = $val['server_id'];
			}
			
			foreach ($otherInfoServer as $key=>$val){
				if(in_array($val['server_id'], $useServerList)){
					unset($otherInfoServer[$key]);
				}
			}			
		}
		
		$this->out['otherInfoServer'] = $otherInfoServer;
	}
	
	public function doAdd(){
		$count = MatchCrossServerVService::crepeat(0, 'cross_server_name', $this->R('cross_server_name'),$this->R('g'));
		if($count > 0){
			$this->showMessage('名称已经存在');
		}else{
			$result = MatchCrossServerVService::doAdd($_POST);
	
			if($result !== false){
				
				$crossList = SystemService::searchInfo('cross');
				$reset_time = $crossList['reset_time'];
				$reset_time_2 = strtotime($reset_time);
				$reset_time_1 = strtotime ("-3 day", strtotime($reset_time));
				$nowTime = strtotime(date('Y-m-d H:i:00',time()));
				if($reset_time_1 < $nowTime && $nowTime < $reset_time_2){  //重置时间的前3天内
					$this->showMessage('新增成功', PubFunc::buildUrl("/oss/?r=matchCrossServerV/index"));
				}else{
					$this->showMessage('新增成功', PubFunc::buildUrl("/oss/?r=matchCrossServerV/handIndex"));
				}
				
			}else{
				$this->showMessage('新增失败');
			}
		}
		 
	
	}
	

    public function edit(){
    	$game = PubBase::getCurrentGame();
        $id = $this->R('id');
        $info = MatchCrossServerVService::get($id);
        
        if(empty($info)) $this->showMessage('找不到该信息');
        
        $this->setTitle('编辑', $info['cross_server_name']);

        $this->out['info'] = $info;

        $backUrl = PubFunc::buildBackUrl("/oss/?r=matchCrossServerV/index");  //返回路径
        $this->out['backUrl'] = $backUrl;
        
        $page = $this->R('page');
        $this->out['page'] = $page;
        
        //查询跨服配置
        $crossList = SystemService::searchInfo('cross');
        $this->out['crossList'] = $crossList;
        
        //当前跨服关联的服务器
        $infoServer = MatchCrossServerVService::getMatchServer($id);
        $this->out['infoServer'] = $infoServer;
        
        //查询能够让匹配跨服选择的服（去除$id本身的关系的服务器）
        $otherInfoServer = MatchCrossServerVService::fitServer($id);
        
        $reset_time = $crossList['reset_time'];
        $reset_time_2 = strtotime($reset_time);
        $reset_time_1 = strtotime ("-3 day", strtotime($reset_time));
        $nowTime = strtotime(date('Y-m-d H:i:00',time()));
        if($reset_time_1 < $nowTime && $nowTime < $reset_time_2){  //重置时间的前3天内
        	$this->setTitle('编辑匹配跨服');
        }else{
        	$this->setTitle('编辑匹配跨服(临时配置)');
        	//这里要剔除正式匹配跨服存在的数据
        	$modMatchCrossSer = new ModMatchCrossSer();
        	$game = PubBase::getCurrentGame();
        	$useServer = $modMatchCrossSer->getAllServer($game);
        	$useServerList = array();
        	foreach ($useServer as $key=>$val){
        		$useServerList[] = $val['server_id'];
        	}
        		
        	foreach ($otherInfoServer as $key=>$val){
        		if(in_array($val['server_id'], $useServerList)){
        			unset($otherInfoServer[$key]);
        		}
        	}
        }
        
        $this->out['otherInfoServer'] = $otherInfoServer;
    }

    public function doEdit(){
        $id = $this->R('id');
        $count = MatchCrossServerVService::crepeat($this->R('id'), 'cross_server_name', $this->R('cross_server_name'),$this->R('g'));
        if($count > 0){
        	$this->showMessage('名称已经存在');
        }else{
        	$result = MatchCrossServerVService::doEdit($id, $_POST);
        	
            if($result['state'] !== false){
            	
            	$crossList = SystemService::searchInfo('cross');
            	$reset_time = $crossList['reset_time'];
            	$reset_time_2 = strtotime($reset_time);
            	$reset_time_1 = strtotime ("-3 day", strtotime($reset_time));
            	$nowTime = strtotime(date('Y-m-d H:i:00',time()));
            	if($reset_time_1 < $nowTime && $nowTime < $reset_time_2){  //重置时间的前3天内
            		$this->showMessage('编辑成功', PubFunc::buildBackUrl("/oss/?r=matchCrossServerV/index"));
            	}else{
            		$this->showMessage('编辑成功', PubFunc::buildBackUrl("/oss/?r=matchCrossServerV/handIndex"));
            	}
        		
        	}else{
        		$this->showMessage('编辑失败');
        	}
        }  
    }
    
    public function delete(){
    	$id = $this->R('id');
    	if($this->isAuth !=1){  //isAuth为1则没有权限
    		$result = MatchCrossServerVService::delete($id);
    		if($result !== false){
    			$this->showMessage('删除成功', PubFunc::buildBackUrl("/oss/?r=matchCrossServerV/index"));
    		}else{
    			$this->showMessage('删除失败', PubFunc::buildBackUrl("/oss/?r=matchCrossServerV/index"));
    		}
    	}
    }
    
    public function formal(){
    	$out = MatchCrossServerVService::formal($ids);
    	$this->out = $out;
    	$this->outType = 'json';
    	
    }
    
    public function handformal(){
    	$ids = PubRequest::R('ids');
    	if($ids == ''){
    		$out = array('status'=>0,'msg'=>'请选择要操作的数据','data'=>'');
    	}else{
    		$out = MatchCrossServerVService::handformal($ids);
    	}
    	$this->out = $out;
    	$this->outType = 'json';
    }
    
    /*
     * 定时任务测试
     * 当当前时间到重置时间时，将未正式生效的匹配跨服的配置发送到游戏端
     * 发送成功，则将记录记入到正式的匹配跨服记录表中，原先的记录标记is_delete为1
     * 然后再删除未正式的的记录
     */
    public function automatic(){
    	$game = 'mango';
    	$crossList = SystemService::searchInfo('cross');
    	$reset_time = $crossList['reset_time'];
    	$nowTime = strtotime(date('Y-m-d H:i:00',time()));  //当前时间
    	if($reset_time != $nowTime){
    		$modMatchCrossServerV = new ModMatchCrossServerV();
    		$modMatchCrossSerV = new ModMatchCrossSerV();
    		$match_obj = $modMatchCrossServerV->findAllByAttributes(array('game'=>$game)); 
    		 		
    		if(!$match_obj){
    			echo "暂无数据 \n";
    			exit;
    		}else{
    			//将正式的匹配跨服is_delete修改为1
    			$modMatchCrossServer = new ModMatchCrossServer();
    			$modMatchCrossServer->updateAll(array('is_delete'=>1),'game =:game and is_delete=:is_delete',array(':game'=>$game,':is_delete'=>0));
    		}
//     		echo '<pre/>';
//     		var_dump($match_obj);exit;
    		$ids = '';
    		$matchCrossData = array();
    		$matchCrossSerData = array();
    		foreach ($match_obj as $key=>$val){
    			$match_id = $val->id;
    			$match_server_obj = $modMatchCrossSerV->findAllByAttributes(array('match_id'=>$match_id));
    			$match_server_ids = '';
    			if(!$match_server_obj){  //若没有关系，则退出循环
    				//直接删除数据
    				$modMatchCrossServerV->deleteByPk($val->id);
    				continue;
    			}
    			foreach ($match_server_obj as $k=>$v){
    				$match_server_ids .= ','.$v->server_id;
    			}
    			$match_server_ids = substr($match_server_ids, 1);
    			echo "match_server_ids == ".$match_server_ids." \n";
    			$send = array();
    			$send['match_server_ids'] = $match_server_ids;
    			$send['node_name'] = $val->node_name;
    			$send['ip'] = $val->ip;
    			$send['port'] = $val->port;
    			//$s_result = self::send($send);
    			$s_result['state'] = true;
    			if($s_result['state']){  //发送成功
    				$ids .= ','.$val->id;
    				//将匹配跨服加到正式的匹配跨服表    				
    				$d = array();
    				$d['id'] = $val->id;
    				$d['game'] = $val->game;
    				$d['cross_server_name'] = $val->cross_server_name;
    				$d['node_name'] = $val->node_name;
    				$d['ip'] = $val->ip;
    				$d['port'] = $val->port;
    				$d['create_user'] = 1;
    				$d['create_time'] = time();
    				$d['update_user'] = 1;
    				$d['update_time'] = time();
    				array_push($matchCrossData, $d);
    				
    				foreach ($match_server_obj as $k=>$v){
    					$d = array();
    					$d['match_id'] = $v['match_id'];
    					$d['server_id'] = $v['server_id'];
    					array_push($matchCrossSerData, $d);
    				}
    				
    			}else{
    				echo $val->cross_server_name."发送失败 \n";
    			}
    		}
    		
    		$modMatchCrossServer = new ModMatchCrossServer();
    		$modMatchCrossServer->addmuch($matchCrossData);
    		$modMatchCrossSer = new ModMatchCrossSer();
    		$modMatchCrossSer->addmuch($matchCrossSerData);
    		
    		//删除发送成功的匹配跨服数据（未生效表）
    		$ids = substr($ids, 1);
    		$modMatchCrossServerV->deleteForIds($ids);
    		$modMatchCrossSerV->deleteForMatchIds($ids);
    		echo "匹配跨服配置自动生效成功 \n";
    	}else{
    		echo "暂未到重置时间 \n";
    	}
    	exit;
    }
    
    
    
    
}